/**
 * 
 */
package com.shine.cotrun.exp;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;

/**
 * @author zsy
 *
 */
public abstract class Export<D> {
	protected ExportConf conf;
	protected File expToFile;//导出文件
	protected String extName;//扩展名
	protected FileOutputStream outputStream;//输出文件流
	
	public Export(ExportConf conf) {
		this.conf = conf;
	}

	public ExportConf getConf() {
		return conf;
	}

	public File getExpToFile() {
		return expToFile;
	}
	
	/**
	 * 取得导出的文件名，包含扩展名
	 * @return
	 */
	public String getFileName() {
		return conf.getExpFileName() + extName;
	}
	
	/**
	 * 准备工作
	 */
	public void init() {
		File dir = new File(conf.getExpToDir());
		 if(!dir.exists()) {
    		if (!dir.mkdirs()) {
    			throw new RuntimeException("文件夹创建失败");
    		}
    	}
		this.expToFile = new File(dir, conf.getExpFileName() + extName);
		try {
			outputStream = new FileOutputStream(expToFile);
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 导出数据可能被调多次，不参关闭文件流
	 * @param pageData 
	 * @param lastPage
	 */
	public abstract void export(Collection<D> data) throws Exception;
	
	/**
	 * 导出结束
	 * @return
	 */
	public String end() {
		try {
			outputStream.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return expToFile.getPath();
	}
}
